package com.cet.algorithm.回溯.子集问题;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * @program: cet-practice
 * @description: 子集2
 * @author: 陈恩涛
 * @create: 2023-05-31 11:07
 **/
public class LC90 {

    List<List<Integer>> result = new LinkedList<>();

    LinkedList<Integer> path = new LinkedList<>();

    boolean[] used;

    public List<List<Integer>> subsetsWithDup(int[] nums) {
        Arrays.sort(nums);
        used = new boolean[nums.length];
        backTracing(nums, 0);
        return result;
    }

    public void backTracing(int[] nums, int startIdx) {

        // 收集所有节点的
        result.add(new LinkedList<>(path));

        for (int i = startIdx; i < nums.length; i++) {

            // 树层去重
            if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) {
                continue;
            }

            // 保证树枝可以使用不同位置的重复元素
            used[i] = true;
            path.add(nums[i]);
            backTracing(nums, i + 1);
            path.removeLast();
            used[i] = false;
        }
    }

    public static void main(String[] args) {
        LC90 lc90 = new LC90();
        System.out.println(lc90.subsetsWithDup(new int[]{1, 2, 2}));
    }
}
